<?php
namespace Go\Controller;
use Pingpp\WxpubOAuth;
class CartController extends BaseController {
	
	private $Mcartlist = null;
	
	protected function _initialize(){
		parent::_initialize();
		$this->Mcartlist = json_decode(stripslashes(cookie('Cartlist')),true);
	}
	
	public function cartlist(){
		$Mcartlist = $this->Mcartlist;
		$shopids='';
		if(is_array($Mcartlist)){
			foreach($Mcartlist as $key => $val){
				$shopids.=intval($key).',';
			}
			$shopids=str_replace(',0','',$shopids);
			$shopids=trim($shopids,',');
		}
		$model = new \Think\Model();
		$shoplist=array();
		if($shopids!=NULL){
			$shoparr = $model->query("SELECT * FROM `__PREFIX__shoplist` where `id` in($shopids)");
			$_temp = array();
			foreach ($shoparr as $key => $value){
				$_temp[$value['id']] = $value;
			}
			$shoparr = $_temp;
		}
		if(!empty($shoparr)){
			foreach($shoparr as $key=>$val){
				if($val['q_end_time']=='' || $val['q_end_time']==NULL){
					$shoplist[$key]=$val;
					$Mcartlist[$val['id']]['num']=$Mcartlist[$val['id']]['num'];
					$Mcartlist[$val['id']]['shenyu']=$val['shenyurenshu'];
					$Mcartlist[$val['id']]['money']=$val['yunjiage'];
				}
			}
		}
		
		cookie('Cartlist',json_encode($Mcartlist));
		
		$MoenyCount=0;
		$Cartshopinfo='{';
		if(count($shoplist)>=1){
			foreach($Mcartlist as $key => $val){
				$key=intval($key);
				if(isset($shoplist[$key])){
					$shoplist[$key]['cart_gorenci']=$val['num'] ? $val['num'] : 1;
					$MoenyCount+=$shoplist[$key]['yunjiage']*$shoplist[$key]['cart_gorenci'];
					$shoplist[$key]['cart_xiaoji']=substr(sprintf("%.3f",$shoplist[$key]['yunjiage']*$val['num']),0,-1);
					$shoplist[$key]['cart_shenyu']=$shoplist[$key]['zongrenshu']-$shoplist[$key]['canyurenshu'];
					$Cartshopinfo.="'$key':{'shenyu':".$shoplist[$key]['cart_shenyu'].",'num':".$val['num'].",'money':".$shoplist[$key]['yunjiage']."},";
				}
			}
		}
		$shop=0;
		if(!empty($shoplist)){
			$shop=1;
		}
		$MoenyCount=substr(sprintf("%.3f",$MoenyCount),0,-1);
		$Cartshopinfo.="'MoenyCount':$MoenyCount}";
		$this->assign('shoplist',$shoplist);
		$this->assign('Mcartlist',$Mcartlist);
		$this->assign('shop',$shop);
		$this->assign('cart_active','active');
		$this->display();
	}
	
	public function pay(){
		if(!$member=$this->userinfo){
			header("location: ".U('Wx/Login/login'));
			exit;
		}
		
		$Mcartlist= $this->Mcartlist;
		$shopids='';
		if(is_array($Mcartlist)){
			foreach($Mcartlist as $key => $val){
				$shopids.=intval($key).',';
			}
			$shopids=str_replace(',0','',$shopids);
			$shopids=trim($shopids,',');
		}
		
		$model = new \Think\Model();
		
		$shoplist=array();
		if($shopids!=NULL){
			$lists = $model->query("SELECT * FROM `__PREFIX__shoplist` where `id` in($shopids)");
			$_temp = array();
			foreach ($lists as $key => $value){
				$_temp[$value['id']] = $value;
			}
			$shoplist=$_temp;
		}
		$MoenyCount=0;
		if(count($shoplist)>=1){
			foreach($Mcartlist as $key => $val){
				$key=intval($key);
				if(isset($shoplist[$key])){
					$shoplist[$key]['cart_gorenci']=$val['num'] ? $val['num'] : 1;
					$MoenyCount+=$shoplist[$key]['yunjiage']*$shoplist[$key]['cart_gorenci'];
					$shoplist[$key]['cart_xiaoji']=substr(sprintf("%.3f",$shoplist[$key]['yunjiage']*$val['num']),0,-1);
					$shoplist[$key]['cart_shenyu']=$shoplist[$key]['zongrenshu']-$shoplist[$key]['canyurenshu'];
					$ten_per = floor($shoplist[$key]['zongrenshu']/1) > 0 ? floor($shoplist[$key]['zongrenshu']/1) : 1;
					$max = $ten_per > $shoplist[$key]['cart_shenyu'] ? $shoplist[$key]['cart_shenyu'] : $ten_per;
					if($val['num'] > $max){
						$this->error($shoplist[$key]['title']."购买数量不能大于");
					}
				}
			}
			$shopnum=0;  //表示有商品
		}else{
			cookie('Cartlist',null);
			//$this->error('购物车没有商品');
			$shopnum=1; //表示没有商品
		}
		$_SESSION['submitcode'] = $submitcode = uniqid();
		// 总支付价格
		$MoenyCount = substr ( sprintf ( "%.3f", $MoenyCount ), 0, - 1 );
		// 会员余额
		$Money = $member ['money'];
		$flag = false;
		$onlineMoenyCount = 0;
		if ($MoenyCount > $Money){
			//10-5
			$onlineMoenyCount = $MoenyCount-$Money;
			//ping++
			$this->pay_path = U('Payment/pay');
			$openid = '';
			if (strpos($_SERVER['HTTP_USER_AGENT'],'MicroMessenger') == true){
				require_once dirname(dirname(__FILE__)).'/Util/pingpp/lib/WxpubOAuth.php';
				$wxset = C('WxPayConf_pub');
				if (!isset($_GET['code'])){
					if (empty($wxset)) {
						$this->error('操作失败');
						exit;
					}
					$redirect = C('WEB_URL').U('Cart/pay');
					header('Location:'.WxpubOAuth::createOauthUrlForCode($wxset['APPID'], $redirect));
					exit;
				}else{
					$openid = WxpubOAuth::getOpenid($wxset['APPID'], $wxset['APPSECRET'], $_GET['code']);
				}
		
			}
			$this->openid = $openid;
			$flag = true;
			
			$this->flag = $flag;
			$this->onlineMoenyCount = $onlineMoenyCount;
			
			$this->gourl = U('Cart/paysubmit',array('checkpay' => 'money','banktype' => 'nobank','submitcode'=>$submitcode));
			
		}
		//ping++end
		
		// 商品数量
		$shoplen = count ( $shoplist );
		
		/*
		$fufen = System::load_app_config ( "user_fufen", '', 'member' );
		if ($fufen ['fufen_yuan']) {
			$fufen_dikou = intval ( $member ['score'] / $fufen ['fufen_yuan'] );
		} else {
			$fufen_dikou = 0;
		}
		*/
		$fufen_dikou = 0;
		//$paylist = $this->db->GetList ( "select * from `@#_pay` where `pay_start` = '1'" );
		
		$paylist = $model->query("SELECT * FROM `__PREFIX__pay` where `pay_start` = '1' AND pay_mobile = 1");
		if (strpos($_SERVER['HTTP_USER_AGENT'],'MicroMessenger') == true){
			foreach ($paylist as $key => $value) {
				if ($value['pay_class'] == 'wapalipay'){
					unset($paylist[$key]);
				}
			}
		}

		$this->assign('shoplist', $shoplist);
		$this->assign('MoenyCount',$MoenyCount);
		$this->assign('Money',$Money);
		$this->assign('shopnum',$shopnum);
		$this->assign('fufen_dikou',$fufen_dikou);
		$this->assign('member',$member);
		$this->assign('paylist',$paylist);
		$this->assign('submitcode',$submitcode);
		$this->display('payment');
	}
	
	public function os(){
		if (IS_AJAX){
			$changeid = isset($_REQUEST['i']) ? $_REQUEST['i'] : '';
			if (!empty($changeid)){
				$model = new \Think\Model();
				$model->execute("delete from `__PREFIX__member_addmoney_record` where `changeid`='$changeid'");
			}
		}else{
			$this->error('非法操作');
		}
	}
	
	// 开始支付
	public function paysubmit() {
		header ( "Cache-control: private" );
		if(!$member=$this->userinfo){
			header("location: ".U('Wx/Login/login'));
			exit;
		}
		$checkpay = I('checkpay'); // 获取支付方式 fufen money bank
		$banktype = I('banktype'); // 获取选择的银行 CMBCHINA ICBC CCB
		$money = I('x'); // 获取需支付金额
		$fufen = I('t'); // 获取福分
		$submitcode1 = I('submitcode'); // 获取SESSION
		$uid = $this->userinfo['uid'];
	   if (! empty ($submitcode1 )) {
		  if (isset ($_SESSION ['submitcode'] )) {
			  $submitcode2 = $_SESSION ['submitcode'];
		  } else {
			  $submitcode2 = null;
		  }
		  if ($submitcode1 == $submitcode2) {
			  unset ($_SESSION["submitcode"]);
		  } else {
			  $this->error('请不要重复提交...');
		  }
	   } else {
			$this->error('正在返回购物车...');
			exit;
	   }
		$zhifutype = M('Pay')->where(array('pay_class' => 'alipay'))->find();
		if (empty($zhifutype)) {
			$this->error('手机支付只支持易宝,请联系站长开通！');
		}
		$pay_checkbox = false; //钱包支付
		$pay_type_bank = false; //银行卡支付
		$pay_type_id = false;   //获取平台支付类型，支付宝，微信支付...
		if ($checkpay == 'money') {
			$pay_checkbox = true;
		}
		if ($banktype != 'nobank') {
			$pay_type_id = $banktype;
		}
		if (! empty ( $zhifutype )) {
			$pay_type_bank = $zhifutype ['pay_class'];
		}
		if (! $pay_type_id) {
			if ($checkpay != 'fufen' && $checkpay != 'money'){
				$this->error('选择支付方式');
			}
		}
		$pay = new \Go\Util\pay();
		$pay->fufen = $checkpay == 'fufen'?$fufen:0;
		$pay->pay_type_bank = $pay_type_bank;
		$ok = $pay->init($uid, $pay_type_id, 'go_record'); // 购买商品
		if ($ok == 'error'){
			$this->error('账户余额不足');
		}
		if ($ok != 'ok') {
			cookie('Cartlist',null);
			$this->error($ok."<br />购物车没有商品请");
		}
		$check = $pay->go_pay($pay_checkbox);
		if (!$check) {
			$this->error('订单添加失败');
		}
		cookie('Cartlist',null);
		if ($check) {
			header ( "location:".U('Cart/paysuccess'));
		} else {
			header ( "location:" . U('Index/index'));
		}
	}
	
	public function paysuccess(){
		cookie('Cartlist',null);
		$this->display();
	}

}